package org.cable.link.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.cable.common.enums.BizCodeEnum;
import org.cable.common.enums.EventMessageType;
import org.cable.common.exception.BizException;
import org.cable.common.model.EventMessage;
import org.cable.link.service.ShortLinkService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author hsj
 * @date 2023/11/6 14:12
 */
@Component
@Slf4j
@RabbitListener(queues = "short_link.update.link.queue")
public class ShortLinkUpdateLinkMqListener {

    @Autowired
    private ShortLinkService shortLinkService;

    @RabbitHandler
    public void shortLinkHandler(EventMessage eventMessage, Message message, Channel channel) throws IOException {
        log.info("ShortLinkUpdateLinkMqListener监听到消息内容:{}",message);
        long tag = message.getMessageProperties().getDeliveryTag();

        try {
            eventMessage.setEventMessageType(EventMessageType.SHORT_LINK_UPDATE_LINK.name());
            shortLinkService.handleUpdateShortLink(eventMessage);
        }catch (Exception e){
            log.error("消费失败:{}",e);
            throw new BizException(BizCodeEnum.MQ_CONSUMER_EXCEPTION);
        }

        log.info("消费成功:{}",eventMessage);
        //确认消费成功
        channel.basicAck(tag,false);

    }
}
